package org.nerve.webmagic;

import org.apache.commons.lang3.StringUtils;
import org.nerve.webmagic.bean.*;
import org.openqa.selenium.*;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.codecraft.webmagic.Site;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

/**
 * org.nerve.webmagic
 * Created by zengxm on 2016/4/21 0021.
 */
public class PhantomjsDriverBuilder implements DriverBuilder<PhantomJSDriver> {
	private static final Logger logger= LoggerFactory.getLogger(PhantomjsDriverBuilder.class);

	@Override
	public PhantomJSDriver build(final SpiderConfig config) throws IOException {
		return configure(config);
	}

	/**
	 * 创建WebDriver
	 * 读取Site中配置信息（包括Proxy，userUgent）
	 * @param config
	 * @throws IOException
	 */
	public PhantomJSDriver configure(final SpiderConfig config) throws IOException {
		DesiredCapabilities caps = DesiredCapabilities.phantomjs();

		/*
		注意：判断平台是Windows还是Linux（只支持64位系统）
		 */
		//判断PhantomJS文件是否存在
		Platform platform=Platform.getCurrent().family();
		File file=new File(this.getClass().getResource("/").getPath()
				+"phantomjs"
				+(platform==Platform.WINDOWS?".exe":""));
		System.out.println("current Platform:"+platform+","+(platform==Platform.WINDOWS));
		if(!file.exists()){
			logger.error(file.getAbsolutePath()+" must exist!");

			throw new FileNotFoundException("PhantomJS file not found on "+file.getAbsolutePath());
		}

		caps.setCapability("takesScreenshot", true);
		caps.setCapability(
				PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
				file.getAbsolutePath()
		);
		//链接超时3分钟
		//caps.setCapability(PhantomJSDriverService.PHANTOMJS_PAGE_SETTINGS_PREFIX+"resourceTimeout", 3*60*1000);

		configWithSite(caps, config);

		/*
		 *  增加PhantomJS的启动参数
		 */
		ArrayList<String> cliArgsCap = new ArrayList<>();
		cliArgsCap.add("--web-security=false");
		cliArgsCap.add("--ssl-protocol=any");
		cliArgsCap.add("--ignore-ssl-errors=true");
		caps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS,cliArgsCap);

		PhantomJSDriver driver=new PhantomJSDriver(caps);
		WebDriver.Options manage = driver.manage();

		//设置大小为1600
		manage.window().setSize(new Dimension(1600, 800));

		//如果设置了初始化的cookies，则传递给webdriver
		if (config.getCookies() != null) {
			for (org.nerve.webmagic.bean.Cookie coo:config.getCookies()){
				manage.addCookie(new Cookie(coo.name,coo.value,coo.path));
			}
		}

		logger.info(">>>>>>>>>>>>> init WebDriver done!"+driver.toString()+" <<<<<<<<<<<<<<<<");
		return driver;
	}

	/**
	 * 配置代理以及userAgent
	 * @param caps
	 * @param config
	 */
	private void configWithSite(final DesiredCapabilities caps,final SpiderConfig config){
		if(StringUtils.isNotBlank(config.getProxyHost())){
			String proxyString=config.toProxyString();
			Proxy proxy=new Proxy();
			proxy.setHttpProxy(proxyString).setFtpProxy(proxyString).setSslProxy(proxyString);
			caps.setCapability(CapabilityType.PROXY, proxy);

			logger.info("proxy settings:"+proxyString);
		}

		if(StringUtils.isNotBlank(config.getUserAgent())){
			caps.setCapability(
					PhantomJSDriverService.PHANTOMJS_PAGE_SETTINGS_PREFIX+"userAgent",
					config.getUserAgent());

			logger.info("userAgent settings:"+config.getUserAgent());
		}
	}
}
